package com.example.hms.service.serviceImpl;

import com.example.hms.dao.UserDao;
import com.example.hms.entity.User;
import com.example.hms.service.UserService;
import com.example.hms.util.Result;
import com.example.hms.util.ResultSubmit;
import com.example.hms.util.TokenUtil;
import com.example.hms.util.UserResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    @Resource
    UserDao userDao;

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Result login(String userId, String userPassword, HttpServletRequest request) {
        User user = userDao.login(userId);
        if(user == null) {
            return ResultSubmit.error("登录失败，用户不存在");
        }else if(userPassword.equals(user.getUserPassword())){
            HttpSession session = request.getSession();
            session.setAttribute("userId",user.getUserId());
            session.setAttribute("userName",user.getUserName());
            session.setAttribute("roleName",user.getRoleName());
            Long time = System.currentTimeMillis();
            session.setAttribute("time",time);
            session.setAttribute("token",TokenUtil.getToken(
                    String.valueOf(user.getUserId()),user.getUserName(),user.getRoleName(),time));

            return ResultSubmit.success(sweet(user));
        }else {
            return ResultSubmit.error("登录失败，密码错误");
        }
    }

    private UserResult sweet(User user) {
        UserResult userResult = new UserResult();
        userResult.setUserId(user.getUserId());
        userResult.setUserName(user.getUserName());
        userResult.setRoleName(user.getRoleName());
        return userResult;
    }

    @Override
    public Result info(HttpServletRequest request){
        HttpSession session = request.getSession();
        // 1. MAP返回
//        Map<String,String> map = new HashMap<>();
//        map.put("userID",session.getAttribute("userId").toString());
//        map.put("userName",session.getAttribute("userName").toString());
//        map.put("roleName",session.getAttribute("roleName").toString());
//        return ResultSubmit.success(map);
        // 2. 包装类返回
        UserResult userResult = new UserResult();
        userResult.setUserId((Integer) session.getAttribute("userId"));
        userResult.setUserName(session.getAttribute("userName").toString());
        userResult.setRoleName(session.getAttribute("roleName").toString());

        // todo 系统记录
        return ResultSubmit.success(userResult);
    }

    @Override
    public Result selectAllUser(String userId, String userName, String roleName){
        List<User> users = userDao.selectAllUser(userId, userName, roleName);
        return ResultSubmit.success(users);
    }

    @Override
    public Result 查询所有用户信息(String 用户ID, String 用户名, String 角色名){
        List<User> 用户列表 = userDao.selectAllUser(用户ID, 用户名, 角色名);
        return ResultSubmit.success(用户列表);
    }

    @Override
    public Result insert(User user){
        user.setCreateTime(format.format(new Date()));
        user.setUserId(    Math.abs(   (int)System.currentTimeMillis()   )   );
        user.setRoleId(2);
        user.setDeleteIdentity("未删除");
        int i = userDao.insert(user);
        // todo 系统记录操作
        if(i == 1){
            return ResultSubmit.success("成功");
        }else {
            // 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultSubmit.error("失败");
        }
    }

    @Override
    public Result 插入(User 用户){
        用户.setCreateTime(format.format(new Date()));
        用户.setUserId(    Math.abs(   (int)System.currentTimeMillis()   )   );
        用户.setRoleId(2);
        用户.setDeleteIdentity("未删除");
        int 插入的结果行数 = userDao.insert(用户);
        // todo 系统记录操作
        if (插入的结果行数 == 1){
            return ResultSubmit.success("成功");
        }else {
            // 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultSubmit.error("失败");
        }
    }

    // 修改
    // 逻辑删除原数据
    // 修改传入数据中的基础信息，比如：删除标识、创建时间
    // 清除userTableId
    // 插入新数据
    // todo 系统记录操作
    // 根据删除方法、新增方法返回值判断逻辑修改整个功能是否执行成功
    // 不成功则返回报错并回滚
    @Override
    public Result update(User user){
        int i = userDao.update(user);
        user.setDeleteIdentity("未删除");
        user.setCreateTime(format.format(new Date()));
        user.setUserTableId(0);
        int j = userDao.insert(user);
        // todo 系统记录操作
        if(i == 1 || j == 1){
            return ResultSubmit.success("成功");
        }else {
            // 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultSubmit.error("失败");
        }
    }

    // 删除
    // 前段传递参数仅为userId
    // 根据userId查询用户信息
    // 根据用户信息执行逻辑删除
    // todo 系统记录操作
    // 根据删除方法返回值判断整个逻辑删除功能是否执行成功
    // 不成功则返回报错并回滚
    @Override
    public Result delete(String userId){
        User user = userDao.login(userId);
        int i = userDao.update(user);
        // todo 系统记录操作
        if(i == 1 ){
            return ResultSubmit.success("成功");
        }else {
            // 手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultSubmit.error("失败");
        }
    }
}
